// pages/home-music/index.js
import {
  rankingStore,
  rankingMap,
  playerStore
} from "../../store/index"

import {
  getBanners,
  getSongMenu
} from '../../service/api_music'
import queryRect from '../../utils/query-rect'
import throttle from '../../utils/throttle'

const throttleQueryRect = throttle(queryRect, 1000, { trailing: true })

Page({
  data: {
    swiperHeight: 0,
    banners: [],
    recommendSongs: [],
    hotSongMenu: [],
    recommendSongMenu: [],
    rankings: { 0: {}, 2: {}, 3: {} },

    currentSong: {},
    isPlaying: false
  },
  onLoad: function (options) {
    // 获取页面数据
    this.getPageData()
    rankingStore.dispatch("getRankingDataAction")

    this.setupPlayerStoreListener()
  },

  // 事件处理
  // 搜索框点击事件
  handleSearchClick: function () {
    wx.navigateTo({
      url: '/packageDetail/pages/detail-search/index'
    })
  },
  // image组件加载完成事件
  handleSwiperImageLoaded: function () {
    throttleQueryRect('.banners-pic').then(res => {
      this.setData({
        swiperHeight: res.height
      })
    })
  },
  handleMoreClick: function() {
    this.navigateToDetailSongsPage('hotRanking')
  },

  handleRankingItemClick: function(event) {
    const idx = event.currentTarget.dataset.idx
    this.navigateToDetailSongsPage(rankingMap[idx])
  },
  hotHandleMoreClick: function() {
    wx.navigateTo({
      url: '/packageDetail/pages/detail-playlist/index',
    })
  },
  navigateToDetailSongsPage: function(rankingName) {
    wx.navigateTo({
      url: `/packageDetail/pages/detail-songs/index?ranking=${rankingName}&type=rank`
    })
  },

  handleSongItemClick: function(event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListIndex", index)
    playerStore.setState("playListSongs", this.data.recommendSongs)
  },

  handlePlayBtnClick: function() {
    playerStore.dispatch("changeMusicPlayStatus", !this.data.isPlaying)
  },

  handlePlayBarClick: function() {
    wx.navigateTo({
      url: '/packagePlayer/pages/music-player/index?id=' + this.data.currentSong.id,
    })
  },

  handleListClick: function() {
    wx.showToast({
      title: '功能还在完善中~~~',
      icon: 'none'
    })
  },

  // 网络请求
  getPageData: function () {
    // 获取轮播图数据
    getBanners().then(res => {
      this.setData({
        banners: res.banners
      })
    })
    // 获取热门歌单数据
    getSongMenu().then(res => {
      this.setData({
        hotSongMenu: res.playlists
      })
    })
    // 获取推荐歌单数据
    getSongMenu("华语").then(res => {
      this.setData({
        recommendSongMenu: res.playlists
      })
    })
  },

  onUnload: function () {

  },

  setupPlayerStoreListener: function() {
    // 排行榜监听
    rankingStore.onState("hotRanking", res => {
      if (!res.tracks) return
      const recommendSongs = res.tracks.slice(0, 6)
      this.setData({
        recommendSongs
      })
    })
    rankingStore.onState("newRanking", this.getRankingHandler(0))
    rankingStore.onState("originRanking", this.getRankingHandler(2))
    rankingStore.onState("upRanking", this.getRankingHandler(3))
    // 播放器监听
    playerStore.onStates(["currentSong", "isPlaying"], ({currentSong, isPlaying}) => {
      if (currentSong) {
        this.setData({ currentSong })
      }
      if (isPlaying !== undefined) this.setData({ isPlaying })
    })
  },

  getRankingHandler: function (idx) {
    return (res) => {
      if (Object.keys(res).length === 0) return
      const name = res.name
      const coverImgUrl = res.coverImgUrl
      const playCount = res.playCount
      const songlist = res.tracks.slice(0, 3)
      const rankingObj = {
        name,
        coverImgUrl,
        songlist,
        playCount
      }
      const newRankings = {...this.data.rankings, [idx]: rankingObj }
      this.setData({
        rankings: newRankings
      })
    }
  }
})